'''
MIT License

Copyright (c) 2023 Anggara Yama Putra

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
import argparse as ap
import json
from pathlib import Path
from base64 import b85encode, b85decode
import lupa.lua53 as lua



def __filecopy (source, target):
    with Path(source).open('rb') as fp_in:
        copy_path = Path( target )
        copy_path.parent.mkdir( parents=True, exist_ok=True )
        with copy_path.open('wb') as fp_out:
            fp_out.write( fp_in.read() )


__parser = ap.ArgumentParser(
    prog='anluac',
    description='Compile Studio Lua scripts.',
)
__parser.add_argument(
    'project_json',
    type=Path,
    help='The project.json file to process',
)
__parser.add_argument(
    '-o',
    '--outdir',
    metavar='path',
    type=Path,
    help='Output directory',
)
__parser.add_argument(
    '-s',
    '--stripdebug',
    action='store_true',
    help='''strip debug information before writing the output file.
This saves some space in very large chunks,
but if errors occur when running a stripped chunk,
then the error messages may not contain the full information they usually do.
For instance, line numbers and names of local variables are lost.''',
)


__args = __parser.parse_args()

# Preparing
project_path = Path( __args.project_json ).resolve( strict=True )
print( 'Project.json:', project_path )
project_parent = project_path.parent
script_outdir = __args.outdir
if not script_outdir:
    script_outdir = (project_parent / './compiled/')
script_outdir = Path( script_outdir )
print( 'Output directory:', script_outdir )
script_outdir.mkdir( parents=True, exist_ok=True )
project = {}
with project_path.open('rb') as fp:
    project = json.load( fp )
base85_name = 'base85.common'
base85_file = 'common/' + base85_name
base85_path = (project_parent / base85_file).resolve(strict=False)
if not base85_path.exists():
    base85_path = Path('lua_common/base85.common').resolve(strict=True)
print( 'Base85 path:', base85_path )
# Copy base85 script.
__filecopy( base85_path, (script_outdir / base85_file) )
stripdebug = __args.stripdebug
print( 'Strip debug info?', stripdebug )
# Init lua runtime.
def __okboomer (*_a, **_k): raise AttributeError( 'access denied' )
luart = lua.LuaRuntime(
    encoding=None,
    register_eval=False,
    attribute_filter=__okboomer,
)

# OK, let's go!
script_rootdir = project_parent
compiled_project = {}
for mod, v in project.items():
    has_base112 = False
    for i, script_name in enumerate(v):
        if not script_name:
            continue
        if base85_name in script_name:
            if i == 0:
                has_base112 = True
            continue
        script_path = (script_rootdir / script_name).resolve( strict=True )
        compiled_path = (script_outdir / script_name).with_suffix( script_path.suffix + '.compiled' )
        compiled_path.parent.mkdir( parents=True, exist_ok=True )
        with compiled_path.open('w', encoding='utf8') as fp:
            print( fp.name )
            strip = ('true' if stripdebug else 'false')
            bytecodes = luart.eval(
                'string.dump('
                f'loadfile("{script_path.as_posix()}")'
                f', {strip})'
            )
            bytecodes = b85encode( bytecodes, pad=False )
            fp.write(
                'assert(load('
                'AnggaraNothing.Base85.decode_as_string("'
                f"{bytecodes.decode('ascii')}"
                '"),"'
                f'{script_name}'
                '"))()'
            )
        compiled_name = Path( script_name )
        compiled_name = compiled_name.with_suffix( compiled_name.suffix + '.compiled' ).as_posix()
        v[i] = compiled_name
    if not has_base112:
        v.insert( 0, base85_file )
    compiled_project[mod] = [*dict.fromkeys(v)]

# Write project.json
with (script_outdir / 'project.json').open('w', encoding='utf8') as fp:
    print( fp.name )
    json.dump( compiled_project, fp, indent=2 )
